package com.itheima.controller;

import com.itheima.pojo.Resource;
import com.itheima.utils.JSONFileUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

@Controller
public class FileController {

    @RequestMapping("/fileUpload")
    public String fileUpload(MultipartFile file, HttpServletRequest request, Model model) {
        try {
            if (!file.isEmpty()) {
                String path = request.getServletContext().getRealPath("/files/");
                File uploadDir = new File(path);
                if (!uploadDir.exists()) {
                    uploadDir.mkdirs();
                }

                String filename = file.getOriginalFilename();
                File uploadFile = new File(path + filename);
                file.transferTo(uploadFile);

                // 保存文件记录到JSON
                saveFileRecord(filename, request);

                // 使用重定向，避免直接返回视图
                return "redirect:/fileupload.jsp?success=true";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 上传失败也重定向
        return "redirect:/fileupload.jsp?success=false";
    }

    @ResponseBody
    @RequestMapping(value = "/getFilesName", produces = "application/json;charset=utf-8")
    public String getFilesName(HttpServletRequest request) throws Exception {
        String path = request.getServletContext().getRealPath("/") + "files/files.json";
        File jsonFile = new File(path);
        if (!jsonFile.exists()) {
            // 如果文件不存在，返回空数组
            return "[]";
        }
        return JSONFileUtils.readFile(path);
    }

    @RequestMapping("/download")
    public ResponseEntity<byte[]> fileDownload(HttpServletRequest request,
                                               String filename) throws Exception {
        String path = request.getServletContext().getRealPath("/files/");
        File file = new File(path + File.separator + filename);

        if (!file.exists()) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }

        HttpHeaders headers = new HttpHeaders();
        filename = getFileName(request, filename);
        headers.setContentDispositionFormData("attachment", filename);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        return new ResponseEntity<>(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.OK);
    }

    private String getFileName(HttpServletRequest request, String filename) throws Exception {
        String agent = request.getHeader("User-Agent");
        if (agent != null && agent.contains("Firefox")) {
            // 修复：使用正确的Base64编码方式
            filename = "=?UTF-8?B?" + Base64.getEncoder()
                    .encodeToString(filename.getBytes("UTF-8")) + "?=";
        } else {
            filename = URLEncoder.encode(filename, "UTF-8");
        }
        return filename;
    }

    private void saveFileRecord(String filename, HttpServletRequest request) throws Exception {
        String path = request.getServletContext().getRealPath("/") + "files/files.json";
        File jsonFile = new File(path);

        List<Resource> resources = new ArrayList<>();
        if (jsonFile.exists()) {
            String json = JSONFileUtils.readFile(path);
            ObjectMapper mapper = new ObjectMapper();
            if (json != null && !json.trim().isEmpty()) {
                resources = mapper.readValue(json,
                        mapper.getTypeFactory().constructCollectionType(List.class, Resource.class));
            }
        }

        // 检查是否已存在同名文件
        boolean exists = false;
        for (Resource resource : resources) {
            if (resource.getName().equals(filename)) {
                exists = true;
                break;
            }
        }

        if (!exists) {
            resources.add(new Resource(filename));

            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(resources);
            JSONFileUtils.writeFile(json, path);
        }
    }
}